package com.dingli.servlet;

import com.dingli.DAO.RegisterAndLoginDAO;
import com.dingli.entity.Person;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Scanner;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/views/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("account");
        String password = request.getParameter("password");
        try {
            RegisterAndLoginDAO loginDAO = new RegisterAndLoginDAO();
            Person user = loginDAO.login(username, password);
            if (user!=null) {
                HttpSession session = request.getSession();
                session.setAttribute("userid", user.getId());
                session.setAttribute("user", user);
                System.out.println(user.getRole());
                if(user.getRole()!=3){
                    session.setAttribute("admin", username);
                    response.sendRedirect("/adminManage");
                } else{
                    session.setAttribute("username", username);
                    response.sendRedirect("/index");
                }
            } else {
                response.sendRedirect("/views/error.jsp");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendRedirect("/views/error.jsp");
        }
    }
}